package com.masterclient.app.modules.purchase;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.baselibrary.bean.goods.ProductSpecificationData;
import com.eoner.baselibrary.bean.order.ConfirmOrderData;
import com.eoner.baselibrary.bean.purchase.PurchaseProductData;
import com.eoner.baselibrary.utils.IntentUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.baselibrary.widget.PurchaseTabLayout;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.modules.firstpager.HomeFragmentPagerAdapter;
import com.masterclient.app.modules.purchase.contract.PurchaseProductContract;
import com.masterclient.app.modules.purchase.contract.PurchaseProductPresenter;
import com.masterclient.app.widget.TitlebarView;
import com.gyf.immersionbar.ImmersionBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

import static com.masterclient.app.modules.purchase.PurchaseProductFragment.GIF_PRODUCT;
import static com.masterclient.app.modules.purchase.PurchaseProductFragment.NORMAL_PRODUCT;

/**
 * Author：hxm
 */
@Route(path = AroutePath.PURCHASE_ACTIVITY)
public class NewPurchaseProductActivity extends BaseActivity<PurchaseProductPresenter> implements PurchaseProductContract.View {

    @BindView(R.id.purchase_bg)
    ImageView purchaseBg;
    @BindView(R.id.purchase_bar)
    TitlebarView purchaseBar;
    @BindView(R.id.tabLayout)
    PurchaseTabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.purchase_shop)
    ImageView purchaseShop;
    @BindView(R.id.purchase_name)
    TextView purchaseName;
    @BindView(R.id.purchase_tel)
    TextView purchaseTel;
    @BindView(R.id.tv_notice)
    TextView tvNotice;
    @BindView(R.id.purchase_bottom_num)
    TextView purchaseBottomNum;
    @BindView(R.id.purchase_bottom_selected_num)
    TextView purchaseBottomSelectedNum;

    private String pageType;
    private PurchaseProductData data;
    private PurchaseProductFragment giftPurchaseProductFragment;
    private PurchaseProductFragment retailPurchaseProductFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_purchase_product);
        ButterKnife.bind(this);

        ImmersionBar.with(this).transparentStatusBar().fitsSystemWindows(false).init();
        purchaseBg.setPadding(0,ImmersionBar.getStatusBarHeight(this),0,0);

        List<Fragment> fragments = new ArrayList<>();
        giftPurchaseProductFragment = PurchaseProductFragment.getInstance(GIF_PRODUCT);
        giftPurchaseProductFragment.setCartNumChangeListener(new PurchaseProductFragment.OnCartNumChangeListener() {
            @Override
            public void setCartNum(long num) {
                setBottom(num);
            }

            @Override
            public void refreshList(String type) {
                pageType = type;
                mPresenter.getData();
            }
        });
        fragments.add(giftPurchaseProductFragment);
        retailPurchaseProductFragment = PurchaseProductFragment.getInstance(NORMAL_PRODUCT);
        retailPurchaseProductFragment.setCartNumChangeListener(new PurchaseProductFragment.OnCartNumChangeListener() {
            @Override
            public void setCartNum(long num) {
                setBottom(num);
            }

            @Override
            public void refreshList(String type) {
                pageType = type;
                mPresenter.getData();
            }
        });
        fragments.add(retailPurchaseProductFragment);

        tabLayout.addTab("礼包商品","已累计拿货量 ",true);
        tabLayout.addTab("零售商品","可享受拿货量对应价格",false);
        HomeFragmentPagerAdapter adapter = new HomeFragmentPagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout.getTabLayout()));
        tabLayout.setupWithViewPager(viewPager);
        (tabLayout.getTabLayout()).getTabAt(0).select();

        mPresenter.getData();
        initListener();
    }

    @OnClick({R.id.purchase_bottom_img,R.id.purchase_see,R.id.purchase_tel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.purchase_see:
            case R.id.purchase_bottom_img:
                ARouter.getInstance().build(AroutePath.PURCHASE_SHOP_CART_ACTIVITY).navigation();
                break;
            case R.id.purchase_tel:
                ConfirmDialog dialog = new ConfirmDialog(this,"是否拨打电话",null,data.getSeller().getMobile(),"取消","确定","#FF6809");
                dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                    @Override
                    public void cancel() {
                        dialog.dismiss();
                    }

                    @Override
                    public void confirm() {
                        IntentUtil.toPhoneApp(NewPurchaseProductActivity.this,data.getSeller().getMobile());
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
        }
    }

    private void initListener() {
        purchaseBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {
                ARouter.getInstance().build(AroutePath.PURCHASE_ORDERS_ACTIVITY)
                        .withString("from_type","purchase").navigation();
            }
        });
    }

    @Override
    public void showData(PurchaseProductData data) {
        if (GIF_PRODUCT.equals(pageType)){
            giftPurchaseProductFragment.finishRefresh();
        }else {
            retailPurchaseProductFragment.finishRefresh();
        }
        if (data == null){
            return;
        }
        this.data = data;
        //更新Tab文案
        String tabStr = "已累计拿货量 " + data.getGrand_total_num() + " 件";
        SpannableString spannableString = new SpannableString(tabStr);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FF5000")), 7, 7+data.getGrand_total_num().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tabLayout.updateSbTab(spannableString);

        //头部信息
        if (data != null && data.getSeller() != null){
            ViewTransformUtil.glideImageView(this, data.getSeller().getLogo(), purchaseShop, new Transformation[]{new CenterCrop(),
                    new RoundedCornersTransformation(ScreenUtils.dp2px(6), 0)}, R.mipmap.defaults);
            purchaseName.setText(data.getSeller().getStore_name());
            if (!TextUtils.isEmpty(data.getSeller().getMask_mobile())){
                purchaseTel.setVisibility(View.VISIBLE);
                purchaseTel.setText(String.format("联系TA %s", data.getSeller().getMask_mobile()));
            }else {
                purchaseTel.setVisibility(View.GONE);
            }
        }

        //公告信息
        tvNotice.setText(data.getNotice_text());

        //礼包商品
        if (data.getGift_products() != null && data.getGift_products().size()>0){
            giftPurchaseProductFragment.refreshData(data);
        }

        //零售商品
        if (data.getNormal_products() != null && data.getNormal_products().size()>0){
            retailPurchaseProductFragment.refreshData(data);
        }

        //底部显示
        setBottom(TextUtils.isEmpty(data.getDealer_cart_num())?0:Long.parseLong(data.getDealer_cart_num()));
    }

    private void setBottom(long num){
        if (num>0){
            purchaseBottomNum.setText(String.valueOf(num));
            purchaseBottomNum.setVisibility(View.VISIBLE);
        }else {
            purchaseBottomNum.setVisibility(View.GONE);
        }
        purchaseBottomSelectedNum.setText(String.format("已选%d件商品", num));
    }

    @Override
    public void showFailure(int type, String msg) {
        if (GIF_PRODUCT.equals(pageType)){
            giftPurchaseProductFragment.finishRefresh();
        }else {
            retailPurchaseProductFragment.finishRefresh();
        }
    }

    @Override
    public void showSpecificationData(ProductSpecificationData specificationData) {

    }

    @Override
    public void successAddCart(Map<String, String> map) {

    }

    @Override
    public void confirmOrderSuccess(ConfirmOrderData data, String isCustody) {

    }
}
